<template>
	<view class="good_detail_panel">
		<!-- Canvas 用于绘制海报 -->
		
		<view class="tab-bar" v-if="istab">
		  <view class="tab-item" @click="scrollToSection('goods',0)" :class="{ active: activeTab === 0 }">商品</view>
		  <view class="tab-item" @click="scrollToSection('details',1)" :class="{ active: activeTab === 1 }">详情</view>
		  <view class="tab-item" @click="scrollToSection('recommend',2)" :class="{ active: activeTab === 2 }">推荐</view>
		</view>
		<view id="goods">
			<view class="good_detail_content">
				<view class="good_img">
					<u-swiper 
					:list="goodsInfo.banner_list" 
					@change="changeLunbo" 
					keyName="banner_img_path" 
					imgMode="aspectFit" 
					height="380px" 
					:indicator="true">
						<view slot="indicator" class="indicator-num">
							<text class="indicator-num__text">{{ current }}/{{ goodsInfo.banner_list.length }}</text>
						</view>
					</u-swiper>
				
				</view>
				<view class="good_content">
					
					<view class="price" v-if="memberLevel > 0">
						<view class="price_left">
							会员价:￥ <text>{{goodsInfo.local_shop_price||''}}</text>
						</view>
						<view class="price_right">
							
							<text>价格￥{{goodsInfo.market_price||''}}</text>
							<text>剩余{{goodsInfo.local_stock_num||''}}</text>
						</view>
					</view>
					<view class="price" v-else>
						<view class="price_left">
							价格:￥ <text>{{goodsInfo.local_shop_price||''}}</text>
						</view>
						<view class="price_right">
							
							<text>价格￥{{goodsInfo.market_price||''}}</text>
							<text>剩余{{goodsInfo.local_stock_num||''}}</text>
						</view>
					</view>
					<view class="good_name">
						<view class="good_namet">{{goodsInfo.product_name||""}}</view>
						<view class="fenxiang" @click="onshowShare">
							<image src="https://img-cdn.duobashuzi.com/xianggui/img/fenxiang.png"></image>
							<text>分享</text>
						</view>
					</view>
					
				</view>
			</view>
			<view class="fg"></view>
			<view class="goodli">
				
				<view class="service-item" @click="paihang" v-if="goodsInfo.rank_msg">
				  <text class="service-title">排行</text>
				  <view class="service-detail paih">
					  <image class="jiangbei" src="https://img-cdn.duobashuzi.com/xianggui/img/jiangbei.png"></image>
					 {{goodsInfo.rank_msg}}</view>
				  <view class="arrow-right"></view>
				</view>
				<view class="fg" v-if="goodsInfo.rank_msg"></view>
				<!-- <view class="service-item">
				  <text class="service-title">配送</text>
				  <text class="service-detail">
					  <text class="service-detailli">快递：免运费</text>
					  <text class="service-detailli">快递：免运费</text>
				  </text>
				  <view class="arrow-right"></view>
				</view> 
				<view class="fg"></view>-->
				<view class="service-item" @click="onshowService" v-if="goodsInfo.goods_service_title == 1">
				  <text class="service-title">服务</text>
				  <text class="service-detail">{{goodsInfo.goods_service_title||""}}</text>
				  <view class="arrow-right"></view>
				</view>
				<view class="fg" v-if="goodsInfo.goods_service_title == 1"></view>
				<view class="service-item" @click="rightBuy(0)" v-if="goodsInfo.is_spec == 1">
				  <text class="service-title">选择</text>
				  <text class="service-detail" v-if="itemTexs">{{itemTexs}}</text>
				  <text class="service-detail" v-else>{{goodsInfo.spec_name}}</text>
				  <view class="arrow-right"></view>
				</view>
			</view>
			<view class="wntj">
				<view class="wntjText" @click="ontuijian">
					<view class="wntjTextleft">为您推荐</view>
					<view class="wntjTextright">
						<text>查看全部</text>
						<view class="arrow-right"></view>
					</view>
				</view>
				<sheet-recommendlb ref="getXgjgoodlistlb"></sheet-recommendlb>
				
			</view>
		</view>
		<view id="details" class="goodlitext">
			<u-parse :content="goodsInfo.details||''" :tagStyle="style"></u-parse>
		</view>
		<view id="recommend"  class="recommendli">
			<u-divider text="更多精选商品"></u-divider>
			<sheet-recommend :isType.sync="isType" ref="getXgjgoodlist"></sheet-recommend>
		</view>
		<view class="botts"></view>
		<canvas canvas-id="posterCanvas" v-show="isCanvas" style="width: 750px;height:1000px;"></canvas>
		<!-- 购买按钮 -->
		<view class="bottom_bar">
			<view class="bottom_barleft">
				<view class="bottom_barli" v-for="(itme,index) in barlist" :key="index" @click="onJump(index)">
					<view class="bottom_barliimg">
						<image :src="itme.src"></image>
						
					</view>
					<view class="bottom_barlitext">{{itme.name}}</view>
					<button v-if="index == 0" class="kefu" type="default" open-type="contact"></button>
					
					<block v-if="index == 1 && countText">
						<text class="num">{{countText}}</text>
					</block>
					<block v-else-if="index == 1 && goodsInfo.cart_num != 0">
						<text class="num">{{goodsInfo.cart_num}}</text>
					</block>
				</view>
			</view>
			<view class="bottom_barright">
				<view class="add_cart" @click="rightBuy(1)">
					加入购物车
				</view>
				
				<button v-if="memberLevel == 0"  class="right_buy" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">立即购买</button>
				<view v-else class="right_buy" @click="rightBuy(2)">
					立即购买
					<!-- memberLevel -->
				</view>
			</view>

		</view>
		<!-- 分享弹窗 -->
		<u-popup :show="showShare" round="10px" mode="bottom" @close="closeShare">
			<view class="share">
				<view class="sharetext">立即分享给好友</view>
				<view class="shareCont">
					<view class="shareli" >
						<image src="https://img-cdn.duobashuzi.com/xianggui/img/weixin.png"></image>
						<text>分享好友</text>
						<button open-type="share" class="custom-style"></button>
						<!-- <u-button openType="share" class="custom-style" text=""></u-button> -->
					</view>
					<!-- <view class="shareli" @click="copyLink">
						<image src="https://img-cdn.duobashuzi.com/xianggui/img/lianjie.png"></image>
						<text>小程序链接</text>
						<text class="xiaohao">分享到朋友圈</text>
					</view> -->
					<view class="shareli" @click="generatePoster">
						<image src="https://img-cdn.duobashuzi.com/xianggui/img/tupian.png"></image>
						<text>生成海报</text>
					</view>
				</view>
				<view class="fg"></view>
				
				<view class="shareqx" @click="closeShare">取消</view>
			</view>
		</u-popup>
		<!-- 服务弹窗 -->
		<u-popup :show="showService" round="10px" mode="bottom" @close="closeService" >
			<view class="w95 h60 pore">
				<u-parse :content="goodsInfo.goods_service_content||''" :tagStyle="style"></u-parse>
				<view class="kong"></view>
				<view  class="addOrder">
					<u-button :loading="load" text="我知道了" shape="circle" @click="closeService"
						color="#ff4444"></u-button>
				</view>
				
			</view>
		</u-popup>
		
		
		
		<sheet-bottom ref="getSpecList" :isCart="isCart" :isSheet.sync="isSheet" :goodsInfo.sync="goodsInfo"
			@closeSheet="closeShee" @itemTex="onitemTex" @count="onCount"></sheet-bottom>
		
	</view>


</template>

<script>
	import {
		logins,
		goodsDetail,
		createXcxCode,
		createShortLink
	} from "@/api/index.js"
	import sheetBottom from "@/components/sheet/sheetBottom.vue"
	import sheetRecommend from "@/components/sheet/sheetRecommend.vue"
	import sheetRecommendlb from "@/components/sheet/sheetRecommendlb.vue"
	import {getPhoneNumber} from '@/api/my.js'
	export default {
		data() {
			return {
				isType:1,
				istab:false,
				isCanvas:false,
				activeTab:0,
				showService:false,
				showShare:false,
				barlist: [{
						src: 'https://img-cdn.duobashuzi.com/xianggui/img/chat.png',
						name: '健康管家',
						link: ""
					},
					{
						src: 'https://img-cdn.duobashuzi.com/xianggui/img/gwc.png',
						name: '购物车',
						link: "/pages/cart/index"
					},
				],
				current:1,
				scrollTop: 0,
				iconStyle: {
					width: '80rpx',
					height: '100rpx'
				},
				tabList: [{
					name: "商品详情"
				}],
				index: 0,

				goods_id: '',
				title: '',
				goodsInfo: {
					banner_list:[]
				},
				isSheet: false,
				phoneNumber: '',
				memberLevel:'',
				isCart: 1, //是否打开购物车，1加购操作，2立即购买
				goodsheight:'',
				detailsheight:'',
				recommendheight:'',
				itemTexs:'',
				countText:'',
				codeImg:'', //小程序码
				option:'',
				style: {
					p: '',
					img: 'display:block;'
				}
			}
		},
		components: {
			sheetBottom,
			sheetRecommend,
			sheetRecommendlb,
			
		},
		onLoad(option) {
			this.option = option;
			console.log('缓存的goodsId是：'+uni.getStorageSync('goodsId'))
			console.log('不带缓存的goodsId是：'+option.id)
			
			
			if(option.id){
				this.goods_id = option.id;
			}else{
				console.log('缓存的goodsId是：'+uni.getStorageSync('goodsId'))
				this.goods_id = uni.getStorageSync('goodsId');
			}
			
			
			if(option.title){
				this.title = option.title;
			}
			console.log('带jwt：'+uni.getStorageSync('jwt'))
			if(!uni.getStorageSync('jwt')){
				this.getLogin();
			}else{
				this.getGoods();
				this.$nextTick(()=>{
					this.$refs.getXgjgoodlistlb.getRecommendlistlb();
					this.$refs.getXgjgoodlist.getRecommendlist();
				})
				
			}
			
			// this.getheight('goods',1);
			// this.getheight('details',2);
			// this.getheight('recommend',3);
			uni.setNavigationBarTitle({
				title: option.title
			});
			
		},
		onShow() {
			this.memberLevel = uni.getStorageSync('memberLevel');
		},
		//自定义分享按钮
		/* onShareAppMessage (res) {
		      let data = {
					title: this.title, //转发标题
					path: 'pages/info/index?id='+ this.goods_id +'&title='+ this.title,
					imageUrl: this.goodsInfo.banner_list[0].banner_img_path //转发图片
		      }
		      return data
		}, */
		onPageScroll(e) {
			if(e.scrollTop >100){
				this.istab = true;
			}else{
				this.istab = false;
			}
			// this.handlePageScroll()
		},
		methods: {
			//授权登录
			getLogin(){
				uni.login({
				  provider: 'weixin',
				  success: (loginRes) => {
				    const code = loginRes.code;
					logins({"code":code}).then(res => {
						uni.setStorageSync("jwt",res.data.jwt)
						
						// this.actList = res.data
						this.getGoods();
						this.$nextTick(()=>{
							this.$refs.getXgjgoodlistlb.getRecommendlistlb();
							this.$refs.getXgjgoodlist.getRecommendlist();
						})
						// this.getBannerList();
						// this.getBannerListTwo();
						// this.topCateTwo();
						// this.getCateGoodsList();
						// this.topbrandList();
						// this.getAbout();
					}).catch(err => {
						uni.showToast({
							title: err.msg,
							icon: "none"
						})
					})
				    // 在这里可以将code发送到后端服务器进行处理
				  }
				});
			},
			// 微信手机号授权
			onGetPhoneNumber(e) {
				// this.privacy()
				if (e.detail.encryptedData) {
					// 使用微信解密接口（需配合后端）
					console.log("微信手机号登录成功:", e.detail);
					console.log("微信手机号登录成功:", e.detail.encryptedData);
					if(e.detail.errMsg==='getPhoneNumber:ok'){
						const data = {
							mobile:e.detail.code
						}
						
						getPhoneNumber(data).then(res=>{
							console.log(res)
							this.memberLevel = res.member_level;
							uni.setStorageSync('memberLevel',res.member_level)
						}).catch(err=>{
							uni.showToast({
								title:err.msg,
								icon:'none'
							})
						})
					}
					
				} else {}
			},
			//获取三个模块的高度
			getheight(id,type){
				let s = id+'height';
				 query.select(`#${id}`).boundingClientRect(data => {
					if(type == 1){
						this.goodsheight = data.height
					}else if(type == 2){
						this.detailsheight = data.height
					}else if(type == 3){
						this.recommendheight = data.height
					}
				 })
				
			},
			//点击分享按钮打开分享弹出
			onshowShare(){
				console.log('点击')
				this.showShare = true;
				this.isCanvas = true;
				this.getCreateXcxCode();
			},
			//顶部锚点
			scrollToSection(id,i) {
				
				this.activeTab = i;  // 更新激活的tab
				  const query = uni.createSelectorQuery().in(this);
			
				  // 获取目标元素的位置信息
				  query.select(`#${id}`).boundingClientRect(data => {
					if (data) {
					  // 滚动页面到指定位置
					  uni.pageScrollTo({
						scrollTop: data.top + uni.getSystemInfoSync().statusBarHeight + 100, // 加上状态栏高度来确保正确显示
						duration: 300  ,// 滚动动画的持续时间
						complete: (e) => {
							console.log(e)
						}
					  });
					}
				  }).exec();
				
				
				
			  },
			  //关闭分享弹窗
			  closeShare(){
			  	this.showShare = false;
				this.isCanvas = false;
				
			  },
			//打开服务弹窗
			onshowService(){
				this.showService = true;
				
			},
			//关闭服务弹窗
			closeService(){
				this.showService = false;
			},
			//轮播图修改
			changeLunbo(i){
				this.current = i.current + 1;
			},
			//跳转到排行页面
			paihang(){
				uni.navigateTo({
					url: '/package/richText/richText?type=1'
				});
			},
			//跳转为您推荐页面
			ontuijian(){
				uni.navigateTo({
					url: '/package/cusinfo/cusinfo?id='+this.goods_id
				});
			},
			
			onJump(e) {
				console.log(e)
				if (e == 1) {
					uni.switchTab({
						url: '/pages/cart/index'
					});
				}
			},
			//生成小程序码
			getCreateXcxCode(data) {
				createXcxCode({
					goods_id: this.goods_id
				}).then(res => {
					console.log(res)
					this.codeImg = res.data.url;
				}).catch(err => {
					uni.showToast({
						title: err.msg,
						icon: "none"
					})
				})
			},
			//获取商品详情
			getGoods(data) {
				if(!this.goods_id){
					console.log('缓存的goodsId是：'+uni.getStorageSync('goodsId'))
					this.goods_id = uni.getStorageSync('goodsId');
				}
				goodsDetail({
					goods_id: this.goods_id
				}).then(res => {
					console.log(res)
					this.goodsInfo = res.result;
					if(this.title == ''){
						uni.setNavigationBarTitle({
							title: res.result.product_name
						});
					}
					
				}).catch(err => {
					uni.showToast({
						title: err.msg,
						icon: "none"
					})
				})
			},
			tabMenu(item) {
				this.index = item.index
			},
			async rightBuy(e) {
				this.isCart = e
				this.isSheet = true
				this.$set(this.goodsInfo, "goods_num", 1)
				if(this.goodsInfo.is_spec == 1){
					this.$nextTick(()=>{
						this.$refs.getSpecList.getgoodsSpecList();
					})
				}
				
				
			

			},
			closeShee(e) {
				this.isSheet = e
			},
			onitemTex(e){
				console.log(e)
				this.itemTexs = e;
			},
			onCount(e){
				console.log(e)
				this.countText = e;
			},
			async generatePoster() {
			      try {
					  this.showShare = false;
					  uni.showToast({
						icon:'loading',
						mask:true,
					  	title: '海报生成中',
						duration:5000
					  });
			
			       const imgRes = await this.downloadImage(this.goodsInfo.banner_list[0].banner_img_path);
				   console.log(this.codeImg)
				   const imgRestwo = await this.downloadImage(this.codeImg);
			        const imgPath = imgRes.tempFilePath;
					const imgPathtwo = imgRestwo.tempFilePath;
					
					setTimeout(() => {
					        this.drawPoster(imgPath,imgPathtwo);
					      }, 100); 
			        
			      } catch (error) {
			        console.error('生成海报时出错:', error);
			        uni.showToast({
			          title: '生成海报时出错，请重试',
			          icon: 'none'
			        });
			      }
				
			    },
				drawPoster(image,imgtwo){
					// 绘制海报
					const posterCtx = uni.createCanvasContext('posterCanvas', this);
					const price = '￥'+ this.goodsInfo.local_shop_price
								
					// 设置海报背景颜色
					posterCtx.setFillStyle('#ffffff');
					posterCtx.fillRect(0, 0, 750, 1000);
					// 绘制商品图片
					posterCtx.drawImage(image, 0, 0, 750, 750); 
								
					// （商品标题）
					posterCtx.setFontSize(32);
					posterCtx.setFillStyle('#000000');
					// posterCtx.fillText(this.goodsInfo.product_name, 10, 770);
					this.wrapText(posterCtx,this.goodsInfo.product_name,10,780,730,40)
					// （价格）
					posterCtx.setFontSize(40);
					posterCtx.setFillStyle('#ff0000');
					posterCtx.fillText(price, 10, 900); 
					
					// 绘制商品图片
					posterCtx.drawImage(imgtwo, 590, 840, 150, 150); 			
					// 将绘制的内容画到Canvas上
					const systemInfo = uni.getSystemInfoSync();
					const pixelRatio = systemInfo.pixelRatio || 2;
					posterCtx.draw(true, () => {
						console.log("触发成功")
					  // 将Canvas内容转换为临时文件路径
					
					  uni.canvasToTempFilePath({
						destWidth: 375 * pixelRatio,
						destHeight: 500 * pixelRatio,
					    canvasId: 'posterCanvas',
					    success: (res) => {
							this.isCanvas = false;
					      console.log('海报生成成功', res.tempFilePath);
					      wx.showShareImageMenu({
					        path: res.tempFilePath
					      })
					    },
					    fail: (err) => {
					      console.error('海报生成失败', err);
					      uni.showToast({
					        title: '海报生成失败，请重试',
					        icon: 'none'
					      });
					    }
					  }, this);
					});
				},
				//图片转为本地路径
				async downloadImage(url) {
				    return new Promise((resolve, reject) => {
				      uni.downloadFile({
				        url: url,
				        success: (res) => {
				          if (res.statusCode === 200) {
				            resolve(res);
				          } else {
				            reject(new Error('下载图片失败'));
				          }
				        },
				        fail: (err) => {
				          reject(err);
				        }
				      });
				    });
				  },
				  //
				  wrapText(ctx, text, x, y, maxWidth, lineHeight) {
					 let currentLine = '';
					   let lines = [];
					   
					   for (let i = 0; i < text.length; i++) {
					     let testLine = currentLine + text[i];
					     let metrics = ctx.measureText(testLine);
					     let testWidth = metrics.width;
						
					     if (testWidth > maxWidth && i > 0) {
					       // 如果加上当前字符后超过了最大宽度，则换行
					       lines.push(currentLine);
					       currentLine = text[i]; // 当前字符作为新行的开始
					       y += lineHeight;
					     } else {
					       // 否则继续添加到当前行
					       currentLine = testLine;
					     }
					   }
					 
					   // 添加最后一行
					   if (currentLine !== '') {
					     lines.push(currentLine);
					   }
					 
					   // 绘制所有行
					   lines.forEach((line, index) => {
						 console.log(`Drawing line ${index + 1}: "${line}" at (${x}, ${y + index * lineHeight})`);
					     ctx.fillText(line, x, y + index * lineHeight);
					   });
				  },
			//点击复制链接
			copyLink() {
				
				createShortLink({
					goods_id: this.goods_id
				}).then(res => {
					console.log(res)
					
				}).catch(err => {
					uni.showToast({
						title: err.msg,
						icon: "none"
					})
				})
			  // uni.showToast({
			  //   title: '该功能正在开发！',
			  //   icon: 'none'
			  // });
				
			},
			queryStringify(obj) {
			      return Object.keys(obj).map(key => `${key}=${encodeURIComponent(obj[key])}`).join('&');
			    },
			 // 处理页面滚动事件
			    handlePageScroll(e) {
			      // 获取当前页面的滚动位置
			      const scrollTop = e.scrollTop;
			      
			      // 如果滚动位置变化较大，避免重复计算
			      if (Math.abs(scrollTop - this.lastScrollTop) < 10) return;
			      
			      // 检查当前滚动位置，并更新 activeTab
			      this.updateActiveTab(scrollTop);
			
			      // 更新上次滚动位置
			      this.lastScrollTop = scrollTop;
			    },
			
			    // 更新 activeTab 的值
			    updateActiveTab(scrollTop) {
			      const query = uni.createSelectorQuery().in(this);
			
			      // 获取每个锚点的位置
			      query.select('#goods').boundingClientRect(data => {
			        if (data && scrollTop >= data.top && scrollTop < data.top + data.height) {
			          this.activeTab = 0;  // 滚动到“商品”锚点
			        }
			      }).select('#details').boundingClientRect(data => {
			        if (data && scrollTop >= data.top && scrollTop < data.top + data.height) {
			          this.activeTab = 1;  // 滚动到“详情”锚点
			        }
			      }).select('#recommend').boundingClientRect(data => {
			        if (data && scrollTop >= data.top && scrollTop < data.top + data.height) {
			          this.activeTab = 2;  // 滚动到“推荐”锚点
			        }
			      }).exec();
			    }
			
		}
		
	}
</script>

<style lang="scss">
	@import 'index.scss';

	.u-back-top {
		background-color: #ff000000 !important;
	}
</style>